import django_filters
from rest_framework import serializers
from django_filters.filterset import FilterSet
from rest_framework.validators import UniqueValidator
from rest_framework.validators import UniqueTogetherValidator
from .models import redisInfo

class RedisDetailSerializer(serializers.ModelSerializer):

    '''
    序列化缓存信息
    '''

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S",read_only=True)

    class Meta:
        model = redisInfo
        fields = "__all__"

class RedisCreateSerializer(serializers.ModelSerializer):

    '''
    新增缓存信息
    '''
    name = serializers.CharField(max_length=20,required=True,validators=[UniqueValidator(queryset=redisInfo.objects.all(),message="名称只能唯一,检查该名称是否已存在")],label="名称",help_text="名称")

    class Meta:
        model = redisInfo
        fields = ("name","env","address","port","password")

        validators = [
            UniqueTogetherValidator(
                queryset=redisInfo.objects.all(),
                fields = ("address","env","port"),
                message="该地址已存在"
            )
        ]

    def hash_md5(self,val):
        '''
        将明文密码加密为MD5
        :param val:
        :return:
        '''
        import hashlib
        md5 = hashlib.md5()
        md5.update(bytes(val,encoding='utf-8'))
        return md5.hexdigest()

    def create(self, validated_data):
        '''
        将通过表单验证无误的数据存储到数据库
        :param validated_data:
        :return:
        '''
        many_to_many = {}
        for field_name, relation_info in validated_data.items():
            if field_name == 'password':
                many_to_many['password'] = self.hash_md5(relation_info)
            else:
                many_to_many[field_name] = relation_info
        instance = redisInfo.objects.create(**many_to_many)
        return instance
